<?php
if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );
/**
*
* @version $Id$
* @package VirtueMart
* @subpackage classes
* @copyright Copyright (C) 2010 Forrest Chamberlain. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details.
*
* http://virtuemart.net
*/

/**
 * CLASS DESCRIPTION
 *                   
 * ps_wishlist
 *
 * The wishlist class is used to store user's wishlists.  A user an add/edit/delete one or more wishlists, as well as
 * making them available for viewing by others.
 * properties:  
 * methods:
 *       add()					validate_add()
 *       update()				validate_update()
 *       delete()				validate_delete()
 *       share()				validate_share()
 *       stopShare()			validate_stopShare()
 *       email()				validate_email()
 *
 *       addItem()				validate_addItem()
 *       updateItem()			validate_updateItem()
 *       deleteItem()			validate_deleteItem()
 *
 *       addToCart()			validate_addToCart()
 *       addItemToCart()		validate_addItemToCart()
 *       cart_add()				validate_cart_add()
 *
 *       get_wishlist()
 *       get_wishlists()
 *       get_wishlist_item()
 *       get_wishlist_items()
 *       get_common_wishlist_items()
 *
 *		 wishlist_code_to_id()
 *
 *       validate_wishlist_owner()
 *       validate_wishlist_item_owner()
 *
 *       get_wishlist_count()
 *       get_product_info()
 *       get_user_info()
*************************************************************************/

class ps_wishlist {
    var $classname = 'ps_wishlist';

    /**
     * Creates a new Wishlist in the table #__{vm}_wishlist
     * @author Forrest
     * @param array $d
	 * @return boolean or int
     */
    function add( &$d ) 
    {
        global $db, $my, $vmLogger, $vmInputFilter;

		$d = $vmInputFilter->safeSQL( $d );

		if ($this->validate_add( $d ))
		{
			$user_id = $my->id;

			$q = "INSERT INTO `#__{vm}_wishlist` ";
			$q .= " (`user_id`, `name`, `comments`, `created`, `modified` ) VALUES ";
			$q .= " ( " . $user_id . ", '" . $d['wishlist_name'] . "', '" . $d['comments'] . "', NOW(), NOW() )";
			$result = $db->query( $q );

			if ($result !== false) 
			{
				$wishlist_id = $db->last_insert_id();
				$code = md5( $wishlist_id . '_' . $user_id );

				$q = 'UPDATE `#__{vm}_wishlist` SET code = \'' . $code . '\' WHERE wishlist_id = ' . $wishlist_id;
				$result = $db->query( $q );

				return $wishlist_id;
			}
			else 
			{
				$vmLogger->debug( $db->getErrorMsg() );
			}
		}

		return false;
	}

	/**
     * Validate a Wishlist add
     * @author Forrest
     * @param array $d
	 * @return boolean
     */
	function validate_add( &$d )
	{
		global $db, $my, $vmLogger, $VM_LANG;

		// VERIFY user_id
		if ((@$_SESSION['auth']['user_id'] != $my->id)  && empty( $my->id ))
		{
            return false;
		}

		// VERIFY name
		if (!isset( $d['wishlist_name'] ) || empty( $d['wishlist_name'] ) || trim( $d['wishlist_name'] ) == '') 
		{
            $vmLogger->warning( $VM_LANG->_('PHPSHOP_WISHLIST_ERROR_NO_NAME') );
            return false;
		}
		$d['wishlist_name'] = trim( $d['wishlist_name'] );

		// VERFIFY no duplicate name
		$q = ' SELECT COUNT( * ) as cnt FROM `#__{vm}_wishlist` ';
		$q .= ' WHERE `user_id` = ' . $my->id;
		$q .= ' AND `name` = \'' . $d['wishlist_name'] . '\'';

		// validate_update calls this function as well... so if there's a wishlist_id, let's make sure we can
		// save the current record with the same name
		if (isset( $d['wishlist_id'] ) && !empty( $d['wishlist_id'] ) && $d['wishlist_id'] > 0 ) 
		{
			$q .= ' AND `wishlist_id` != ' . $d['wishlist_id'];
		}
		$result = $db->query( $q );

		if ($result !== false)
		{
			$row = $db->loadAssocList();
			$row = $row[0];

			if ($row['cnt'] > 0)
			{
				$vmLogger->warning( $VM_LANG->_('PHPSHOP_WISHLIST_ERROR_DUPLICATE_NAME') );
				return false;
			}
		}
		else
		{
			$vmLogger->debug( $db->getErrorMsg() );
			return false;
		}
		
		// VALIDATE comments
		if ( !isset($d['comments']) || empty($d['comments']) || trim( $d['comments'] ) == '' ) 
		{
			/*
            $vmLogger->warning( $VM_LANG->_('PHPSHOP_WISHLIST_ERROR_NO_COMMENT') );
            return false;
			 */
			$d['comments'] = '';
		} 
		else
		{
			$d['comments'] = trim( $d['comments'] );
		}

		return true;
	}

	/**
     * Updates a Wishlist in the table #__{vm}_wishlist
     * @author Forrest
     * @param array $d
	 * @return boolean
     */
    function update( &$d ) 
    {
        global $db, $my, $VM_LANG, $vmLogger, $vmInputFilter;

		$d = $vmInputFilter->safeSQL( $d );

		if ($this->validate_update( $d ))
		{

			$q = " UPDATE `#__{vm}_wishlist` ";
			$q .= " SET `name` = '" . $d['wishlist_name'] . "', ";
			$q .= " `comments` = '" . $d['wishlist_comments'] . "', ";
			$q .= " `modified` = NOW() ";
			$q .= " WHERE `wishlist_id` = " . $d['wishlist_id'];
			$q .= " AND `user_id` = " . $my->id;
			$result = $db->query( $q );

			if ($result !== false)
			{
				$vmLogger->info( $VM_LANG->_('PHPSHOP_WISHLIST_SUCCESS_SAVED') );
				$GLOBALS['func'] = '';

				return true;
			}
			else
			{
				$vmLogger->debug( $db->getErrorMsg() );
			}
		}

		return false;
	}

	/**
     * Validate a Wishlist update
     * @author Forrest
     * @param array $d
	 * @return boolean
     */
	function validate_update( &$d )
	{
		global $my, $vmLogger;

		// VERIFY wishlist_id
		if (!isset( $d['wishlist_id'] ) || empty( $d['wishlist_id'] ) || $d['wishlist_id'] < 1 ) 
		{
            return false;
		}

		// VERIFY everything the validate_add function verifies...
		if (!$this->validate_add( $d ))
		{
			return false;
		}

		// VERIFY we're either an admin, or the user who created this list
		if ( !$GLOBALS['perm']->check( "admin,storeadmin" ) )
		{
			if (!$this->validate_wishlist_owner( $d['wishlist_id'] ))
			{
				$GLOBALS['vmLogger']->warning( $GLOBALS['VM_LANG']->_('PHPSHOP_WISHLIST_ERROR_NO_PERM') );
				return false;
			}
		}

		return true;
	}

	/**
     * DELETES a Wishlist in the table #__{vm}_wishlist
	 * and associated items in the table #__{vm}_wishlist_items
     * @author Forrest
     * @param array $d
	 * @return boolean
     */
    function delete( &$d ) 
    {
        global $db, $vmLogger, $VM_LANG, $vmInputFilter;

		$d = $vmInputFilter->safeSQL( $d );

		if ($this->validate_delete( $d ))
		{

			$q = " DELETE FROM `#__{vm}_wishlist` ";
			$q .= " WHERE `wishlist_id` = " . $d['wishlist_id'];
			$result = $db->query( $q );

			if ($result !== false) 
			{
				$q = " DELETE FROM `#__{vm}_wishlist_items` ";
				$q .= " WHERE `wishlist_id` = " . $d['wishlist_id'];
				$result = $db->query( $q );

				if ($result !== false)
				{
					$vmLogger->info( $VM_LANG->_('PHPSHOP_WISHLIST_REMOVE_SUCCESS') );
					$GLOBALS['wishlist_id'] = '';
					$d['wishlist_id'] = '';

					return true;
				}
				else
				{
					$vmLogger->debug( $db->getErrorMsg() );
				}
			}
			else
			{
				$vmLogger->debug( $db->getErrorMsg() );
			}
		}

		return false;
	}
	/**
     * Validate a Wishlist delete operation
     * @author Forrest
     * @param array $d
	 * @return boolean
     */
	function validate_delete( &$d )
	{
		global $my, $vmLogger;

		// VERIFY user_id
		if ((@$_SESSION['auth']['user_id'] != $my->id)  && empty( $my->id )) 
		{
            return false;
		}

		// VERIFY wishlist_id
		if (!isset( $d['wishlist_id'] ) || empty( $d['wishlist_id'] ) || $d['wishlist_id'] < 1 ) 
		{
            return false;
		}

		// VERIFY we're either an admin, or the user who created this list
		if ( !$GLOBALS['perm']->check( "admin,storeadmin" ) )
		{
			if (!$this->validate_wishlist_owner( $d['wishlist_id'] ))
			{
				$GLOBALS['vmLogger']->warning( $GLOBALS['VM_LANG']->_('PHPSHOP_WISHLIST_ERROR_NO_PERM') );
				return false;
			}
		}

		return true;
	}

	/**
     * Shares a Wishlist in the table #__{vm}_wishlist
     * @author Forrest
     * @param array $d
	 * @return boolean or int
     */
    function share( &$d ) 
    {
        global $db, $my, $vmLogger, $vmInputFilter;

		$d = $vmInputFilter->safeSQL( $d );

		if ($this->validate_share( $d ))
		{
			$q = 'UPDATE `#__{vm}_wishlist` ';
			$q .= ' SET `public` = \'Y\' ';
			$q .= ' WHERE `wishlist_id` = ' . $d['wishlist_id'];
			$result = $db->query( $q );

			if ($result !== false) 
			{
				return true;
			}
			else 
			{
				$vmLogger->debug( $db->getErrorMsg() );
			}
		}

		return false;
	}

	/**
     * Validate sharing a Wishlist
     * @author Forrest
     * @param array $d
	 * @return boolean
     */
	function validate_share( &$d )
	{
		global $db, $my, $vmLogger, $VM_LANG;

		// VERIFY user_id
		if ((@$_SESSION['auth']['user_id'] != $my->id)  && empty( $my->id ))
		{
            return false;
		}

		// VERIFY wishlist_id
		if (!isset( $d['wishlist_id'] ) || empty( $d['wishlist_id'] ) || $d['wishlist_id'] < 1 ) 
		{
            return false;
		}

		// VERIFY we're either an admin, or the user who created this list
		if ( !$GLOBALS['perm']->check( "admin,storeadmin" ) )
		{
			if (!$this->validate_wishlist_owner( $d['wishlist_id'] ))
			{
				$GLOBALS['vmLogger']->warning( $GLOBALS['VM_LANG']->_('PHPSHOP_WISHLIST_ERROR_NO_PERM') );
				return false;
			}
		}

		return true;
	}

	/**
     * Stops sharing a Wishlist in the table #__{vm}_wishlist
     * @author Forrest
     * @param array $d
	 * @return boolean or int
     */
    function stopShare( &$d ) 
    {
        global $db, $my, $vmLogger, $vmInputFilter;

		$d = $vmInputFilter->safeSQL( $d );

		if ($this->validate_stopShare( $d ))
		{
			$q = 'UPDATE `#__{vm}_wishlist` ';
			$q .= ' SET `public` = \'N\' ';
			$q .= ' WHERE `wishlist_id` = ' . $d['wishlist_id'];
			$result = $db->query( $q );

			if ($result !== false) 
			{
				return true;
			}
			else 
			{
				$vmLogger->debug( $db->getErrorMsg() );
			}
		}

		return false;
	}

	/**
     * Validate sharing a Wishlist
     * @author Forrest
     * @param array $d
	 * @return boolean
     */
	function validate_stopShare( &$d )
	{
		return $this->validate_share( $d );
	}

	/**
     * Emails a public Wishlist
     * @author Forrest
     * @param array $d
	 * @return boolean or int
     */
    function email( &$d ) 
    {
        global $db, $my, $vmLogger, $VM_LANG, $vmInputFilter, $mosConfig_sitename, $mosConfig_fromname, $mosConfig_lang;

		$d = $vmInputFilter->process( $d );

		if ($this->validate_email( $d ))
		{
			
			$q = 'SELECT * from #__{vm}_vendor ';
			$q .= 'WHERE vendor_id = \'' . $_SESSION['ps_vendor_id'] . '\'';
			$result = $db->query($q);

			if ($result !== false)
			{
				$db->next_record();

				$from_email = $db->f( "contact_email" );
				$from_name = $mosConfig_fromname;

				$user_name = $GLOBALS['my']->name;
				$user_email = $GLOBALS['my']->email;

				$wl = $this->get_wishlist( $d['wishlist_id'] );
				if ($wl)
				{
					$site_link = URL;
					$wishlist_link = URL . 'index.php?option=com_virtuemart&page=wishlist.index&wishlist_code=' . $wl['code'];
					$subject = $user_name . ' ' . $VM_LANG->_('PHPSHOP_WISHLIST_EMAIL_SUBJECT');

					$file = VM_THEMEPATH . 'templates/wishlist/emails/email_' . $mosConfig_lang . '.txt';
					if (!file_exists( $file ))
					{
						$file = VM_THEMEPATH . 'templates/wishlist/emails/email_english.txt';
					}
					if (file_exists( $file ))
					{
						$body = read_file( $file );

						// replace vars in template
						$body = str_replace( "{site_name}", $mosConfig_sitename, $body );
						$body = str_replace( "{site_link}", $site_link, $body );
						$body = str_replace( "{user_name}", $user_name, $body );
						$body = str_replace( "{user_email}", $user_email, $body );
						$body = str_replace( "{user_message}", $d['wishlist_email_comments'], $body );
						$body = str_replace( "{wishlist_link}", $wishlist_link, $body );

						$addresses = split(',', trim( $d['wishlist_email_addresses'], ',; ' ) );
						foreach ($addresses as $k=>$adr)
						{
							$to_email = trim($adr);
							$mail = vmMail( $from_email, $from_name, $to_email, $subject, $body, '' );
						}
						$vmLogger->info( $VM_LANG->_('PHPSHOP_WISHLIST_SUCCESS_EMAILED') );
						$GLOBALS['page'] = 'wishlist.index';
						return true;
					}
				}
				else
				{
					$vmLogger->debug( $VM_LANG->_('PHPSHOP_WISHLIST_ERROR_EMAIL_NO_FILE') );
				}
			}

		}
		return true;
	}

	/**
     * Validate sharing a Wishlist
     * @author Forrest
     * @param array $d
	 * @return boolean
     */
	function validate_email( &$d )
	{
		global $vmInputFilter, $vmLogger, $VM_LANG, $perm;

		// VALIDATE current user is logged-in
		if (!isset( $GLOBALS['my'] ) || !isset( $GLOBALS['my']->id ) || $GLOBALS['my']->id <= 0) 
		{
			// this page will display a login form...
			$GLOBALS['page'] = 'wishlist.index';
            return false;
		}

		// VALIDATE wishlist_id
		if (!isset( $d['wishlist_id'] ) || empty( $d['wishlist_id'] ) || $d['wishlist_id'] < 1)
		{
			$GLOBALS['page'] = 'wishlist.share';
			return false;
		}

		// VALIDATE email addresses
		// convert to plain text
		$d['wishlist_email_addresses'] = $vmInputFilter->decode( $d['wishlist_email_addresses'] );

		if (!isset( $d['wishlist_email_addresses'] ) || empty( $d['wishlist_email_addresses'] ) || trim( $d['wishlist_email_addresses'], ',; ' ) == '')
		{
			$vmLogger->warning( $VM_LANG->_('PHPSHOP_WISHLIST_ERROR_NO_EMAIL') );
			$GLOBALS['page'] = 'wishlist.share';
			return false;
		}

		$addresses = split( ',', trim( $d['wishlist_email_addresses'], ',; ' ) );
		foreach ($addresses as $k=>$adr)
		{
			$adr = trim($adr);

		}

		// VALIDATE message
		// convert to plain text
		$d['wishlist_email_comments'] = stripslashes( $vmInputFilter->decode( $d['wishlist_email_comments'] ) );

		return true;

	}

	/**
 	 * adds an item to a wishlist
 	 * @author Forrest
 	 * @param array $d
	 * @return boolean
	 */
	function addItem( &$d ) 
	{
		global $db, $vmInputFilter, $my, $vmLogger, $VM_LANG, $perm, $auth;
		require_once( CLASSPATH . 'ps_product_attribute.php' );
		require_once( CLASSPATH . 'ps_product.php' );
		$ps_product = new ps_product();

		$d = $vmInputFilter->safeSQL( $d );

		/* REDIRECTIONS -- if not enough information is presented, redirect to the appropriate page */

		// verify USER ID
		if (!isset( $GLOBALS['my'] ) || !isset( $GLOBALS['my']->id ) || $GLOBALS['my']->id <= 0)
		{
			// this page will display a login form...
			$GLOBALS['page'] = 'wishlist.add_item';
            return true;
		}

		// check for ATTRIBUTES 
		// - if no attributes, we need to ensure we get them
		// - the wishlist.add_item page will display the attributes
		// - if we haven't converted them into a description in $d['description']
		if (!isset( $d['description'] ) || $d['description'] == '')
		{
			$result = ps_product_attribute::cartGetAttributes( $d );

			if ( ( $result["attribute_given"] == false && !empty( $result["advanced_attribute_list"] ) ) ||
				( $result["custom_attribute_given"] == false && !empty( $result["custom_attribute_list"] )) )
			{
				$vmLogger->tip( $VM_LANG->_('PHPSHOP_CART_SELECT_ITEM') );
				$GLOBALS['page'] = 'wishlist.add_item';
				return true;
			}
		}
		$d['product_description'] = $d['description'];
		$d['description'] = $ps_product->getDescriptionWithTax( $d['product_description'], $d['product_id'] );


		// CHECK for wishlist_name -- if it exists, we try to add a new wishlist
		if (isset( $d['wishlist_name'] ) && !empty( $d['wishlist_name'] ) && $d['wishlist_name'] != '') 
		{
			$d['wishlist_id'] = '';
			$result = $this->add( $d );

			if ($result && $result > 0)
			{
				$d['wishlist_id'] = $result;
				$_REQUEST['wishlist_id'] = $d['wishlist_id'];
			}
			else
			{
				$GLOBALS['page'] = 'wishlist.add_item';
				return true;
			}
		} 
		elseif (!isset( $d['wishlist_id'] ) || empty( $d['wishlist_id'] ) || $d['wishlist_id'] < 1) 
		{
			$vmLogger->info( $VM_LANG->_('PHPSHOP_WISHLIST_ERROR_NO_WISHLIST') );
			$GLOBALS['page'] = 'wishlist.add_item';
			return true;
		}

		if ($this->validate_addItem( $d ))
		{

			// check for a duplicate item
			$q = ' SELECT `wishlist_item_id`, `product_quantity` FROM `#__{vm}_wishlist_items` ';
			$q .= ' WHERE `product_id` = ' . $d['product_id'];
			$q .= ' AND `product_description` = \'' . $d['product_description'] . '\'';
			$q .= ' AND `wishlist_id` = \'' . $d['wishlist_id'] . '\'';
			$result = $db->query( $q );

			$dup_wishlist_item_id = 0;
			if ($result !== false)
			{
				$rows = $db->loadAssocList();
				//print_r($rows);
				$row = $rows[0];


				$dup_wishlist_item_id = $row['wishlist_item_id'];
				$d['quantity'] += $row['product_quantity'];
			}
		
			if ($dup_wishlist_item_id > 0)
			{
				$d['wishlist_item_id'] = $dup_wishlist_item_id;
				return $this->updateItem( $d );
			}
			else
			{
				$q = " INSERT INTO `#__{vm}_wishlist_items` ";
				$q .= " (`wishlist_id`, `product_id`, `product_quantity`, `product_description`, `created`, `modified` ) VALUES ";
				$q .= " ( " . $d['wishlist_id'] . ", '" . $d['product_id'] . "', '" . $d['quantity'] . "', '" . $d['product_description'] . "', NOW(), NOW() )";
				$result = $db->query( $q );

				if ($result !== false) 
				{
					$GLOBALS['page'] = 'wishlist.index';
					return $db->last_insert_id();
				}
			}

			$vmLogger->debug( $db->getErrorMsg() );
			return false;
		}

		return false;

	}

	/**
     * Validate adding an Item to a Wishlist
     * @author Forrest
     * @param array $d
	 * @return boolean
     */
	function validate_addItem( &$d )
	{
		global $my, $VM_LANG, $vmLogger;

		// VERIFY user_id
		if ((@$_SESSION['auth']['user_id'] != $my->id)  && empty( $my->id )) 
		{
            return false;
		}

		// VERIFY wishlist_id
		if (!isset( $d['wishlist_id'] ) || empty( $d['wishlist_id'] ) || $d['wishlist_id'] < 1 ) 
		{
            return false;
		}

		// verify PRODUCT ID
		if ( !isset($d['product_id']) || empty($d['product_id']) || $d['product_id'] < 1 ) 
		{
			$vmLogger->warning( $VM_LANG->_('PHPSHOP_PRODUCT_NOT_FOUND') );
			return false;
		}

		// verify QUANTITY
		if ($d['quantity'] < 0) 
		{
			$vmLogger->warning( $VM_LANG->_('PHPSHOP_CART_ERROR_NO_NEGATIVE') );
			return false;
		}
		if (!preg_match( "/^[0-9]*$/", $d['quantity'] )) 
		{
			$vmLogger->warning( $VM_LANG->_('PHPSHOP_CART_ERROR_NO_VALID_QUANTITY') );
			return false;
		}

		return true;
	}
	/**
 	 * updates an item in a wishlist
 	 * @author Forrest
 	 * @param array $d
	 * @return boolean
	 */
	function updateItem( &$d ) 
	{
		global $db, $vmInputFilter, $vmLogger;

		$d = $vmInputFilter->safeSQL( $d );

		if ($this->validate_updateItem( $d ))
		{
		
			$q = ' UPDATE `#__{vm}_wishlist_items` ';
			$q .= ' SET `product_quantity` = ' . $d['quantity'] . ',';
			$q .= ' `modified` = NOW()';
			$q .= ' WHERE `wishlist_item_id` = ' . $d['wishlist_item_id'];
			$result = $db->query( $q );

			if ($result !== false) 
			{
				$GLOBALS['page'] = 'wishlist.index';
				return true;
			}

			$vmLogger->debug( $db->getErrorMsg() );
			return false;
		}

		return false;

	}

	/**
     * Validate updating an Item in a Wishlist
     * @author Forrest
     * @param array $d
	 * @return boolean
     */
	function validate_updateItem( &$d )
	{
		global $my, $VM_LANG, $vmLogger;

		// VERIFY wishlist_id
		if (!isset( $d['wishlist_id'] ) || empty( $d['wishlist_id'] ) || $d['wishlist_id'] < 1 ) 
		{
            return false;
		}

		// verify QUANTITY
		if ($d['quantity'] < 0) 
		{
			$vmLogger->warning( $VM_LANG->_('PHPSHOP_CART_ERROR_NO_NEGATIVE') );
			return false;
		}
		if (!preg_match( "/^[0-9]*$/", $d['quantity'] )) 
		{
			$vmLogger->warning( $VM_LANG->_('PHPSHOP_CART_ERROR_NO_VALID_QUANTITY') );
			return false;
		}

		// VERIFY we're either an admin, or the user who created this list
		if ( !$GLOBALS['perm']->check( "admin,storeadmin" ) )
		{
			if (!$this->validate_wishlist_item_owner( $d['wishlist_item_id'] ))
			{
				$GLOBALS['vmLogger']->warning( $GLOBALS['VM_LANG']->_('PHPSHOP_WISHLIST_ERROR_NO_PERM') );
				return false;
			}
		}

		return true;
	}

	/**
 	 * deletes an item from a wishlist
 	 * @author Forrest
 	 * @param array $d
	 * @return boolean
	 */
	function deleteItem( &$d ) 
	{
		global $db, $vmInputFilter;

		$d = $vmInputFilter->safeSQL( $d );

		if ($this->validate_deleteItem( $d ))
		{
			$q = " DELETE FROM `#__{vm}_wishlist_items` ";
			$q .= " WHERE `wishlist_item_id` = " . $d['wishlist_item_id'];

			$result = $db->query( $q );

			if ($result !== false) 
			{
				$GLOBALS['page'] = 'wishlist.index';
				return true;
			}

			$vmLogger->debug( $db->getErrorMsg() );
			return false;
		}
	}

	/**
     * Validate deleting an Item from a Wishlist
     * @author Forrest
     * @param array $d
	 * @return boolean
     */
	function validate_deleteItem( &$d )
	{
		global $my, $VM_LANG, $vmLogger;

		// VERIFY user_id
		if ((@$_SESSION['auth']['user_id'] != $my->id) && empty( $my->id )) 
		{
            return false;
		}

		// VERIFY wishlist_item_id
		if (!isset( $d['wishlist_item_id'] ) || empty( $d['wishlist_item_id'] ) || $d['wishlist_item_id'] < 1 ) 
		{
            return false;
		}

		// VERIFY we're either an admin, or the user who created this list
		if ( !$GLOBALS['perm']->check( "admin,storeadmin" ) )
		{
			if (!$this->validate_wishlist_item_owner( $d['wishlist_item_id'] ))
			{
				$GLOBALS['vmLogger']->warning( $GLOBALS['VM_LANG']->_('PHPSHOP_WISHLIST_ERROR_NO_PERM') );
				return false;
			}
		}

		return true;
	}

	/**
 	 * add all items in a wishlist to the cart
 	 * @author Forrest
 	 * @param array $d
	 * @return boolean
	 */
	function addToCart( &$d ) 
	{
		global $my, $VM_LANG, $vmLogger;

		require_once( CLASSPATH . 'ps_cart.php' );

		$d = $GLOBALS['vmInputFilter']->safeSQL( $d );

		if ($this->validate_addToCart( $d ))
		{
			$wl_items = $this->get_wishlist_items( $d['wishlist_id'] );

			foreach ($wl_items as $wl_item)
			{
				$wl_item['description'] = $wl_item['product_description'];
				$wl_item['quantity'] = $wl_item['product_quantity'];

				$this->cart_add( $wl_item );
			}

			return true;
		}
		return false;
	}
	/**
     * Validate adding all items in a wishlist to the Cart
     * @author Forrest
     * @param array $d
	 * @return boolean
     */
	function validate_addToCart( &$d )
	{
		global $my, $VM_LANG, $vmLogger;

		// is this catalogue-only?  then we can't add to cart
		if (USE_AS_CATALOGUE == '1')
		{
			return false;
		}

		// VERIFY wishlist_item_id
		if (!isset( $d['wishlist_id'] ) || empty( $d['wishlist_id'] ) || $d['wishlist_id'] < 1 ) 
		{
            return false;
		}

		return true;
	}

	/**
 	 * add an item to the cart from a wishlist
 	 * @author Forrest
 	 * @param array $d
	 * @return boolean
	 */
	function addItemToCart( &$d ) 
	{
		global $my, $VM_LANG, $vmLogger;

		require_once( CLASSPATH . 'ps_cart.php' );

		$d = $GLOBALS['vmInputFilter']->safeSQL( $d );

		if ($this->validate_addItemToCart( $d ))
		{
			$wl_item = $this->get_wishlist_item( $d['wishlist_item_id'] );
			$wl_item['description'] = $wl_item['product_description'];
			$wl_item['quantity'] = $wl_item['product_quantity'];

			return $this->cart_add( $wl_item );
		}
		return false;
	}
	
	/**
     * Validate adding a wishlist item to a Cart
     * @author Forrest
     * @param array $d
	 * @return boolean
     */
	function validate_addItemToCart( &$d )
	{
		global $my, $VM_LANG, $vmLogger;

		// is this catalogue-only?  then we can't add to cart
		if (USE_AS_CATALOGUE == '1')
		{
			return false;
		}

		// VERIFY user_id
		if ((@$_SESSION['auth']['user_id'] != $my->id)  && empty( $my->id )) 
		{
            return false;
		}

		// VERIFY wishlist_item_id
		if (!isset( $d['wishlist_item_id'] ) || empty( $d['wishlist_item_id'] ) || $d['wishlist_item_id'] < 1 ) 
		{
            return false;
		}

		return true;
	}


	/**
	 * Adds a product directly to the cart
	 *  - most of this is copied from ps_cart.
	 *  - unfortunately, ps_cart::add checks for attributes, 
	 *  - and we want to add the description directly
	 * STATIC function
	 * @access private
     * @author Forrest
     * @param array $d
	 * @return boolean
     */
	function cart_add( &$d )
	{
		global $db, $vmLogger;

		require_once( CLASSPATH . 'ps_cart.php' );

		$d = $GLOBALS['vmInputFilter']->safeSQL( $d );

		// VALIDATON - no other validation necessary.  Most validation should have
		// been done by the function that called us (this is a private function)
		if ($this->validate_cart_add( $d ))
		{

			// Check to see if checking stock quantity
			if (CHECK_STOCK) 
			{
				$q = "SELECT product_in_stock ";
				$q .= "FROM #__{vm}_product where product_id='" . $d['product_id'] . "'";
				$db->query($q);
				$db->next_record();
				$product_in_stock = $db->f("product_in_stock");
				if (empty( $product_in_stock )) 
				{
					$product_in_stock = 0;
				}
				if ($d['quantity'] > $product_in_stock) 
				{
					$msg = $VM_LANG->_('PHPSHOP_CART_QUANTITY_EXCEEDED');
					
					$vmLogger->tip( $msg );
					$GLOBALS['page'] = 'shop.waiting_list';
					return true;
				}
			}

			// Check to see if product published
			$q = "SELECT product_publish";
			$q .= " FROM #__{vm}_product where product_id='" . $d['product_id'] . "'";
			$db->query($q);
			$db->next_record();
			$product_pub = $db->f("product_publish");

			$updated = false;
			// Check for duplicate and do not add to current quantity
			for ($i=0; $i < $_SESSION["cart"]["idx"]; $i++) 
			{
				// modified for advanced attributes
				if ($_SESSION['cart'][$i]["product_id"] == $d['product_id'] &&
					$_SESSION['cart'][$i]["description"] == $d["description"]) 
				{
					$updated = true;
				}
			}
			// If we did not update then add the item
			if ((!$updated) && ($product_pub == "Y")) 
			{
				$k = $_SESSION['cart']["idx"];

				$_SESSION['cart'][$k]["quantity"] = $d['quantity'];
				$_SESSION['cart'][$k]["product_id"] = $d['product_id'];
				// added for the advanced attribute modification
				$_SESSION['cart'][$k]["description"] = $d["description"];
				$_SESSION['cart']["idx"]++;
			}
			else
			{
				$old_func = $GLOBALS['func'];
				$GLOBALS['func'] = 'cartAdd'; // need to fool the update function
				ps_cart::update( $d );
				$GLOBALS['func'] = $old_func;
			}

			/* if the cart was updated we gotta update any coupon discounts to avoid ppl getting free stuff */
			if (!empty( $_SESSION['coupon_discount']) ) 
			{
				// Update the Coupon Discount !!
				$_POST['do_coupon'] = 'yes';
			}

			$cart = $_SESSION['cart'];

			return true;
		}
		return false;
	}

	/**
	 * Validate adding a wishlist item to the shopping cart
	 * @author Forrest
	 * @param array $d
	 * @return boolean
	 */
	function validate_cart_add( &$d )
	{
		global $vmLogger;

		$d['quantity'] = ( $d['quantity'] ? $d['quantity'] : 1 );

		// Check for negative quantity
		if ($d['quantity'] < 0) 
		{
			$vmLogger->warning( $VM_LANG->_('PHPSHOP_CART_ERROR_NO_NEGATIVE') );
			return false;
		}

		if (!preg_match("/^[0-9]*$/", $d['quantity'])) 
		{
			$vmLogger->warning( $VM_LANG->_('PHPSHOP_CART_ERROR_NO_VALID_QUANTITY') );
			return false;
		}

		return true;
	}

	/**
	 * Save cart contents as a Wishlist
	 * STATIC function
     * @author Forrest
     * @param array $d
	 * @return array or boolean
     */
	function addCartToWishList( &$d )
	{
		global $my, $VM_LANG, $vmLogger;

		require_once( CLASSPATH . 'ps_cart.php' );

		$d = $GLOBALS['vmInputFilter']->safeSQL( $d );


		/* REDIRECTIONS -- if not enough information is presented, redirect to the appropriate page */

		// verify USER ID
		if (!isset( $GLOBALS['my'] ) || !isset( $GLOBALS['my']->id ) || $GLOBALS['my']->id <= 0)
		{
            return false;
		}

		// CHECK for wishlist_name -- if it exists, we try to add a new wishlist
		if (isset( $d['wishlist_name'] ) && !empty( $d['wishlist_name'] ) && $d['wishlist_name'] != '') 
		{
			$d['wishlist_id'] = '';
			$result = $this->add( $d );

			if ($result && $result > 0)
			{
				$d['wishlist_id'] = $result;
			}
			else
			{
				return true;
			}
		} 
		elseif (!isset( $d['wishlist_id'] ) || empty( $d['wishlist_id'] ) || $d['wishlist_id'] < 1) 
		{
			$vmLogger->info( $VM_LANG->_('PHPSHOP_WISHLIST_ERROR_NO_WISHLIST') );
			return true;
		}

		if ($this->validate_addCartToWishList( $d ))
		{
			for ($i = 0; $i < $_SESSION['cart']["idx"]; $i++)
			{
				// add item?
				$item = array();

				$item['wishlist_id'] = $d['wishlist_id'];
				$item['quantity'] = $_SESSION['cart'][$i]["quantity"];
				$item['product_id'] = $_SESSION['cart'][$i]["product_id"];
				$item['description'] = $_SESSION['cart'][$i]["description"];

				$this->addItem( $item );
			}

			$_REQUEST['wishlist_id'] = $d['wishlist_id'];
			$vmLogger->info( $VM_LANG->_('PHPSHOP_WISHLIST_SUCCESS_CART_SAVED') );
			return true;
		}
		return false;
	}

	/**
	 * Validate adding the shopping cart to a wishlist
	 * @author Forrest
	 * @param array $d
	 * @return boolean
	 */
	function validate_addCartToWishList( &$d )
	{
		// VERIFY wishlist_id
		if (!isset( $d['wishlist_id'] ) || empty( $d['wishlist_id'] ) || $d['wishlist_id'] < 1 ) 
		{
            return false;
		}

		// VERIFY cart contents
		if (!isset( $_SESSION['cart'] ) || empty( $_SESSION['cart'] ) || count( $_SESSION['cart'] ) == 0)
		{
			return false;
		}

		return true;
	}

	/**
	 * Return a Wishlist from the table #__{vm}_wishlist
	 * STATIC function
     * @author Forrest
     * @param int $wishlist_id
	 * @return array or boolean
     */
	function get_wishlist( $wishlist_id )
	{
		global $db, $vmLogger, $my, $perm, $vmInputFilter;

		$wishlist_id = $vmInputFilter->safeSQL( $wishlist_id );

		$q = 'SELECT  w.*, COUNT( wi.wishlist_item_id ) as item_count ';
		$q .= ' FROM `#__{vm}_wishlist` w ';
		$q .= ' LEFT JOIN `#__{vm}_wishlist_items` wi ';
		$q .= ' ON w.wishlist_id = wi.wishlist_id ';
		$q .= ' WHERE w.wishlist_id = ' . $wishlist_id;

		if ( !$perm->check( "admin,storeadmin" ) )
		{
			$q .= ' AND ( w.public = \'Y\' || w.user_id = ' . $my->id . ') ';	
		}

		$q .= ' GROUP BY w.wishlist_id ';

		$result = $db->query( $q );

		if ($result !== false)
		{
			$rows = $db->loadAssocList();

			if (count( $rows ) > 0)
			{
				$row = $rows[0];

				$row['name'] = $vmInputFilter->decode( stripslashes( $row['name'] ) );
				$row['comments'] = $vmInputFilter->decode( stripslashes( $row['comments'] ) );

				return $row;
			}
		}
		else
		{
			$vmLogger->debug( $db->getErrorMsg() );
		}
		return false;
	}


	/**
	 * Generates a list of Wishlists from the table #__{vm}_wishlist
	 * for the particular user id
	 * STATIC function
     * @author Forrest
     * @param int $user_id
	 * @return array or boolean
     */
	function get_wishlists( $user_id = '', $keyword = '', $orderby = 'created ASC', $limitstart = 0, $limit = 0 )
	{
		global $db, $vmLogger, $my, $perm, $vmInputFilter;

		if ($user_id == '' && !$perm->check( 'admin,storeadmin' ))
		{
			$user_id = $my->id;
		}

		$user_id = $vmInputFilter->safeSQL( $user_id );

		$q = 'SELECT  w.*, COUNT( wi.wishlist_item_id ) as item_count ';
		$q .= ' FROM `#__{vm}_wishlist` w ';
		$q .= ' LEFT JOIN `#__{vm}_wishlist_items` wi ';
		$q .= ' ON w.wishlist_id = wi.wishlist_id ';
		$q .= ' WHERE ';

		if ($user_id != '')
		{
			$q .= ' w.user_id = ' . $user_id . ' AND ';
		}

		if ($user_id != '' && $user_id != $my->id && !$perm->check( "admin,storeadmin" ) )
		{
			$q .= ' w.public = \'Y\' AND ';
		}

		if ($keyword != '')
		{
			$q .= ' (';
			$q .= ' w.name LIKE \'%' . $keyword . '%\' OR ';
			$q .= ' w.comments LIKE \'%' . $keyword . '%\' ';
			$q .= ' ) AND';
		}

		$q .= ' 1=1 GROUP BY w.wishlist_id ';

		if ($orderby != '')
		{
			$q .= 'ORDER BY ' . $orderby;
		}

		if ($limitstart != $limit && $limit > 0)
		{
			$q .= ' LIMIT ' . $limitstart . ', ' . $limit;
		}

		$result = $db->query( $q );

		if ($result !== false)
		{
			$rows = $db->loadAssocList();

			foreach ($rows as $k=>$row) 
			{
				$rows[$k]['name'] = $vmInputFilter->decode( stripslashes( $row['name'] ) );
				$rows[$k]['comments'] = $vmInputFilter->decode( stripslashes( $row['comments'] ) );
			}

			return $rows;
		}

		$vmLogger->debug( $db->getErrorMsg() );
		return false;
	}	
	
	/**
	 * Return a Wishlist item from the table #__{vm}_wishlist_items
	 * STATIC function
     * @author Forrest
     * @param int $wishlist_item_id
	 * @return array or boolean
     */
	function get_wishlist_item( $wishlist_item_id )
	{
		global $db, $vmLogger, $my, $perm, $vmInputFilter;

		require_once( CLASSPATH . 'ps_product.php' );
		$ps_product = new ps_product();

		$wishlist_item_id = $vmInputFilter->safeSQL( $wishlist_item_id );

		$q = 'SELECT  wi.* ';
		$q .= ' FROM `#__{vm}_wishlist_items` wi ';
		$q .= ' INNER JOIN `#__{vm}_wishlist` w ';
		$q .= ' ON w.wishlist_id = wi.wishlist_id ';
		$q .= ' WHERE wi.wishlist_item_id = ' . $wishlist_item_id;

		if ( !$perm->check( "admin,storeadmin" ) )
		{
			$q .= ' AND ( w.public = \'Y\' || w.user_id = ' . $my->id . ' ) ';	
		}

		$result = $db->query( $q );

		if ($result !== false)
		{
			$rows = $db->loadAssocList();
			$row = $rows[0];

			$p_row = ps_wishlist::get_product_info( $row['product_id'] );

			$row['product_name'] = $p_row['product_name'];
			$row['product_thumb_image'] = $p_row['product_thumb_image'];
			$row['product_link'] = $p_row['product_link'];
			$row['product_attributes'] = $p_row['product_attributes'];
			$row['product_s_desc'] = $p_row['product_s_desc'];
			$row['product_desc'] = $p_row['product_desc'];

			$row['product_price'] = $ps_product->show_price( $row['product_id'] );
			$row['description'] = $ps_product->getDescriptionWithTax( $row['product_description'], $row['product_id'] );

			return $row;
		}

		$vmLogger->debug( $db->getErrorMsg() );
		return false;
	}

	/**
	 * Return Wishlist items from the table #__{vm}_wishlist_items
	 * STATIC function
     * @author Forrest
     * @param int $wishlist_id
	 * @return array or boolean
     */
	function get_wishlist_items( $wishlist_id )
	{
		global $db, $vmLogger, $my, $perm, $vmInputFilter;

		require_once( CLASSPATH . 'ps_product.php' );
		$ps_product = new ps_product();

		$wishlist_id = $vmInputFilter->safeSQL( $wishlist_id );

		$q = 'SELECT  wi.* ';
		$q .= ' FROM `#__{vm}_wishlist_items` wi ';
		$q .= ' INNER JOIN `#__{vm}_wishlist` w ';
		$q .= ' ON w.wishlist_id = wi.wishlist_id ';
		$q .= ' WHERE w.wishlist_id = ' . $wishlist_id;

		if ( !$perm->check( "admin,storeadmin" ) )
		{
			$q .= ' AND ( w.public = \'Y\' || w.user_id = ' . $my->id . ' ) ';	
		}

		$result = $db->query( $q );

		if ($result !== false)
		{
			$rows = $db->loadAssocList();

			$new_rows = array();
			foreach ($rows as $k=>$row) 
			{

			$query = 'SELECT product_publish'
	        		. ' FROM #__vm_product'
	        		. ' WHERE product_id = '.$row['product_id'];
			$db->query( $query);
			$is_published = $db->f("product_publish");

				if ( ($is_published == "Y") || ( $perm->check( "admin,storeadmin" ) ) ) {

				$new_rows[$k] = $row;
				$new_rows[$k]['description'] = $ps_product->getDescriptionWithTax( $row['product_description'], $row['product_id'] );
				$new_rows[$k]['has_attributes'] =  $row['product_description'];
				$new_rows[$k]['product_price'] = $ps_product->show_price( $row['product_id'] );

				$p_row = ps_wishlist::get_product_info( $row['product_id'] );
				$new_rows[$k]['product_name'] = $p_row['product_name'];
				$new_rows[$k]['product_thumb_image'] = $p_row['product_thumb_image'];
				$new_rows[$k]['product_link'] = $p_row['product_link'];
				$new_rows[$k]['product_attributes'] = $p_row['product_attributes'];
				$new_rows[$k]['product_s_desc'] = $p_row['product_s_desc'];
				$new_rows[$k]['product_desc'] = $p_row['product_desc'];

				}
			
			}
			return $new_rows;
		}

		$vmLogger->debug( $db->getErrorMsg() );
		return false;
	}

	/**
	 * Return the Most Common Wishlist items from the table #__{vm}_wishlist_items
	 * STATIC function
	 * @access admin,storeadmin
     * @author Forrest
	 * @return array or boolean
     */
	function get_common_wishlist_items( $keyword = '', $limitstart, $limit )
	{
		global $db, $vmLogger, $my, $perm, $vmInputFilter;

		if ( $perm->check( "admin,storeadmin" ) )
		{
			$q = 'SELECT p.*, COUNT( wi.product_id ) as item_count ';
			$q .= ' FROM `#__{vm}_product` p';
			$q .= ' INNER JOIN `#__{vm}_wishlist_items` wi';
			$q .= ' ON p.product_id = wi.product_id ';

			if ($keyword != '')
			{
				$q .= ' WHERE p.product_name LIKE \'%' . $keyword . '%\'';
				$q .= ' OR p.product_sku LIKE \'%' . $keyword . '%\'';
			}

			$q .= ' GROUP BY p.product_id';
			$q .= ' ORDER BY item_count DESC';

			if ($limitstart != $limit && $limit > 0)
			{
				$q .= ' LIMIT ' . $limitstart . ', ' . $limit;
			}

			$result = $db->query( $q );

			if ($result !== false)
			{
				return $db->loadAssocList();
			}
			$vmLogger->debug( $db->getErrorMsg() );
		}
		else
		{
			$vmLogger->warning( $GLOBALS['VM_LANG']->_('PHPSHOP_WISHLIST_ERROR_NO_PERM') );
		}

		return false;
	}

	/**
	 * Return the Most Common Wishlist items COUNT from the table #__{vm}_wishlist_items
	 * STATIC function
	 * @access admin,storeadmin
     * @author Forrest
	 * @return array or boolean
     */
	function get_common_wishlist_items_count( $keyword = '')
	{
		global $db, $vmLogger, $my, $perm, $vmInputFilter;

		if ( $perm->check( "admin,storeadmin" ) )
		{
			$q = 'SELECT p.*, COUNT( wi.product_id ) as item_count ';
			$q .= ' FROM `#__{vm}_product` p';
			$q .= ' INNER JOIN `#__{vm}_wishlist_items` wi';
			$q .= ' ON p.product_id = wi.product_id ';

			if ($keyword != '')
			{
				$q .= ' WHERE p.product_name LIKE \'%' . $keyword . '%\'';
				$q .= ' OR p.product_sku LIKE \'%' . $keyword . '%\'';
			}

			$q .= ' GROUP BY p.product_id';
			$q .= ' ORDER BY item_count DESC';

			$result = $db->query( $q );

			if ($result !== false)
			{
				return $db->loadAssocList();
			}
			$vmLogger->debug( $db->getErrorMsg() );
		}
		else
		{
			$vmLogger->warning( $GLOBALS['VM_LANG']->_('PHPSHOP_WISHLIST_ERROR_NO_PERM') );
		}

		return false;
	}

	/**
	 * Return the Most Common Wishlist item Users from the table #__{vm}_user_info
	 * STATIC function
	 * @access admin,storeadmin
     * @author Forrest
	 * @return array or boolean
     */
	function get_common_wishlist_item_users( $wishlist_prod_id, $keyword = '', $limitstart, $limit )
	{
		global $db, $vmLogger, $my, $perm, $vmInputFilter;
		if ( $perm->check( "admin,storeadmin" ) )
		{
			$q = 'SELECT u.user_id, u.first_name, u.last_name, u.user_email';
			$q .= ' FROM #__vm_user_info AS u, #__vm_wishlist AS w,';
			$q .= ' #__vm_wishlist_items AS wi';
			$q .= ' WHERE (wi.product_id = '.$wishlist_prod_id;
			$q .= ' AND wi.wishlist_id = w.wishlist_id';
			$q .= ' AND u.user_id = w.user_id)';

			if ($keyword != '')
			{
				$q .= ' AND (u.first_name LIKE \'%' . $keyword . '%\'';
				$q .= ' OR u.last_name LIKE \'%' . $keyword . '%\')';
			}

			$q .= ' ORDER BY u.user_id';

			if ($limitstart != $limit && $limit > 0)
			{
				$q .= ' LIMIT ' . $limitstart . ', ' . $limit;
			}

			$result = $db->query( $q );

			if ($result !== false)
			{
				return $db->loadAssocList();
			}
			$vmLogger->debug( $db->getErrorMsg() );
		}
		else
		{
			$vmLogger->warning( $GLOBALS['VM_LANG']->_('PHPSHOP_WISHLIST_ERROR_NO_PERM') );
		}

		return false;
	}

	/**
	 * Return the Most Common Wishlist item Users COUNT from the table #__{vm}_user_info
	 * STATIC function
	 * @access admin,storeadmin
     * @author Forrest
	 * @return array or boolean
     */
	function get_common_wishlist_item_users_count( $wishlist_prod_id, $keyword = '')
	{
		global $db, $vmLogger, $my, $perm, $vmInputFilter;

		if ( $perm->check( "admin,storeadmin" ) )
		{
			$q = 'SELECT u.user_id, u.first_name, u.last_name, u.user_email';
			$q .= ' FROM #__vm_user_info AS u, #__vm_wishlist AS w,';
			$q .= ' #__vm_wishlist_items AS wi';
			$q .= ' WHERE (wi.product_id = '.$wishlist_prod_id;
			$q .= ' AND wi.wishlist_id = w.wishlist_id';
			$q .= ' AND u.user_id = w.user_id)';

			if ($keyword != '')
			{
				$q .= ' AND (u.first_name LIKE \'%' . $keyword . '%\'';
				$q .= ' OR u.last_name LIKE \'%' . $keyword . '%\')';
			}

			$q .= ' ORDER BY u.user_id';

			$result = $db->query( $q );

			if ($result !== false)
			{
				return $db->loadAssocList();
			}
			$vmLogger->debug( $db->getErrorMsg() );
		}
		else
		{
			$vmLogger->warning( $GLOBALS['VM_LANG']->_('PHPSHOP_WISHLIST_ERROR_NO_PERM') );
		}

		return false;
	}


	/**
	 * Convert wishlist_code to wishlist_id
	 * @access public
	 * @author Forrest
	 * @param int $user_id
	 * @return boolean
	 */
	function wishlist_code_to_id( $wishlist_code )
	{
		global $db;

		$wishlist_code = $GLOBALS['vmInputFilter']->safeSQL( $wishlist_code );

		// VALIDATE wishlist_code
		if (!isset( $wishlist_code ) || empty( $wishlist_code ) || strlen( trim($wishlist_code) ) != 32)
		{
			return false;
		}
		$wishlist_code = trim($wishlist_code);

		$q = 'SELECT wishlist_id FROM `#__{vm}_wishlist`';
		$q .= ' WHERE code = \'' . $wishlist_code . '\'';

		$result = $db->query( $q );

		if ($result !== false)
		{
			$rows = $db->loadAssocList();

			if (count( $rows ) > 0)
			{
				return $rows[0]['wishlist_id'];
			}
		}
		else
		{
			$GLOBALS['vmLogger']->warning( $db->getErrorMsg() );
		}

		return false;
	}

	/**
	 * Checks that the current user is the owner
	 * of the specified wishlist item
	 * @author Forrest
	 * @param array $d
	 * @return boolean
	 */
	function validate_wishlist_item_owner( $wishlist_item_id )
	{
		global $db, $my, $vmLogger, $VM_LANG, $vmInputFilter;

		$wishlist_item_id = $vmInputFilter->safeSQL( $wishlist_item_id );

		$q = 'SELECT count(*) as cnt FROM `#__{vm}_wishlist` w ';
		$q .= ' INNER JOIN `#__{vm}_wishlist_items` wi ';
		$q .= ' ON w.wishlist_id = wi.wishlist_id ';
		$q .= ' WHERE wi.wishlist_item_id = ' . $wishlist_item_id;
		$q .= ' AND w.user_id = ' . $my->id;	

		$result = $db->query( $q );

		if ($result !== false) 
		{
			$rows = $db->loadAssocList();
			
			if (count( $rows ) > 0)
			{
				$row = $rows[0];
				if ($row['cnt'] > 0)
				{
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * Checks that the current user is the owner
	 * of the specified wishlist item
	 * @author Forrest
	 * @param array $d
	 * @return boolean
	 */
	function validate_wishlist_owner( $wishlist_id )
	{
		global $db, $my, $vmLogger, $VM_LANG, $vmInputFilter;

		$wishlist_id = $vmInputFilter->safeSQL( $wishlist_id );

		$q = 'SELECT count(*) as cnt FROM `#__{vm}_wishlist` ';
		$q .= ' WHERE wishlist_id = ' . $wishlist_id;
		$q .= ' AND user_id = ' . $my->id;	

		$result = $db->query( $q );

		if ($result !== false) 
		{
			$rows = $db->loadAssocList();
			
			if (count( $rows ) > 0)
			{
				$row = $rows[0];
				if ($row['cnt'] > 0)
				{
					return true;
				}
			}
		}
		return false;
	}


	/**
	 * Returns the number of wishlists for the specified (or logged-in) user
	 * STATIC function
     * @author Forrest
     * @param int $user_id
	 * @return int or boolean
     */
	function get_wishlist_count( $user_id = '' )
	{
		global $db, $vmLogger, $my, $perm, $vmInputFilter;

		if ($user_id == '' && !$perm->check( 'admin,storeadmin' ))
		{
			$user_id = $my->id;
		}
		elseif ($user_id != '')
		{
			// this can be called by a module -- thus vmInputFilter is not initialized
			if (isset( $vmInputFilter ))
			{
				$user_id = $GLOBALS['vmInputFilter']->safeSQL( $user_id );
			}
			else
			{
				$user_id = mysql_real_escape_string( $user_id );
			}
		}

		$q = 'SELECT COUNT(*) as cnt ';
		$q .= ' FROM `#__{vm}_wishlist` ';
		$q .= ' WHERE ';

		if ($user_id != '')
		{
			$q .= ' user_id = ' . $user_id . ' AND ';
		}

		if ($user_id != '' && $user_id != $my->id && !$perm->check( "admin,storeadmin" ) )
		{
			$q .= ' public = \'Y\' AND ';
		}
		$q .= ' 1=1 ';

		$result = $db->query( $q );

		if ($result !== false)
		{
			if ($db->next_record())
			{
				return $db->f( 'cnt' );
			}
		}
		else
		{
			$vmLogger->debug( $db->getErrorMsg() );
		}

		return false;
	}
	

	/**
	 * Returns product information that is pertinent to
	 * the wishlist module
	 * STATIC function
     * @author Forrest
     * @param int $product_id
	 * @return array or boolean
     */
	function get_product_info( $product_id )
	{
		global $db, $vmLogger, $VM_LANG, $my, $perm, $vmInputFilter, $sess;

		require_once( CLASSPATH . 'ps_product.php' );
		$ps_product = new ps_product();

		if (!isset( $product_id ) || empty( $product_id ) || $product_id < 1 ) 
		{
			$vmLogger->debug( $VM_LANG->_('PHPSHOP_PRODUCT_NOT_FOUND') );
            return false;
		}

		$product_id = $vmInputFilter->safeSQL( $product_id );

		// QUERY PRODUCT
		$q = 'SELECT * FROM `#__{vm}_product` ';
		$q .= ' WHERE `product_id` =' . $product_id;
		$result = $db->query( $q );

		if ($result !== false)
		{
			$row = $db->loadAssocList();
			$row = $row[0];

			$link_product_id = $row['product_id'];
			$row['product_attributes'] = "";

			// product has PARENT?
			if ( $row['product_parent_id'] != 0 )
			{
				// parent found, query parent
				$q = 'SELECT * FROM #__{vm}_product ';
				$q .= ' WHERE product_id = ' . $row['product_parent_id'];
				$result = $db->query( $q );

				if ($result !== false)
				{
					// overwrite product with certain parent attributes
					if (!$row['product_thumb_image'])
					{
						$row['product_thumb_image'] = $db->f( 'product_thumb_image' );
					}
					$link_product_id = $row['product_parent_id'];

					// get product attributes
					$db_detail = $ps_product->attribute_sql( $row["product_id"], $row['product_parent_id'] );
					while ($db_detail->next_record()) 
					{
						$row['product_attributes'] .= "<br />" . $db_detail->f("attribute_name") . "&nbsp;";
						$row['product_attributes'] .= "(" . $db_detail->f("attribute_value") . ")";
					}
				}
			}

			$row['product_name'] = $vmInputFilter->decode( stripslashes( $row[ 'product_name' ] ) );
			if( $row[ 'product_publish' ] == 'N' )
			{
				$row['product_name'] .= ' (' . $VM_LANG->_('CMN_UNPUBLISHED') . ')';
			}

			$row['product_thumb_image'] = $ps_product->image_tag( $row['product_thumb_image'], "alt=\"" . $row['product_name'] . "\"", 1 );
			$row['product_link'] = JRoute::_('index.php?option=com_virtuemart&page=shop.product_details&product_id=' . $link_product_id);

			return $row;
		}

		$vmLogger->debug( $db->getErrorMsg() );
		return false;
	}

	/**
	 * Get user information
	 * @param int $user_id
	 * @author Forrest
	 * @return mosUser A Joomla user object
	 */
	function get_user_info( $user_id ) {
		global $mainframe, $vmInputFilter;

		$user_id = $vmInputFilter->safeSQL( $user_id );

		if (isset( $user_id ) && is_numeric( $user_id ) && $user_id > 0)
		{

			$user =& JFactory::getDBO();

			$q = "SELECT * FROM #__users ";
			$q .= " WHERE id = " . $user_id;

			$result = $user->setQuery( $q );

			if ($result !== false)
			{
				$result = $user -> loadObject();

				if ($result !== false)
				{
					$name = $result->name;
					if ($name == "") {
					$name = " ";
					}
					return $name;
				}
			}

		}
		return false;
	}

}

?>
